exports.main = async (event, context) => {
  const db = uniCloud.database()
  const userId = event.userId
  const scoreToAdd = event.score

  try {
    // 原子操作更新积分
    const res = await db.collection('user').doc(userId).update({
      score: db.command.inc(scoreToAdd)
    })

    if (res.updated === 1) {
      // 获取更新后的用户数据
      const userRes = await db.collection('user').doc(userId).get()
      return {
        code: 200,
        msg: '积分更新成功',
        data: userRes.data[0]
      }
    } else {
      return {
        code: 500,
        msg: '用户不存在'
      }
    }
  } catch (e) {
    return {
      code: 500,
      msg: '服务器错误：' + e.message
    }
  }
}